#!/usr/bin/env bash
# Copyright (C) 2023 - 2030 huang <vm@vmosc.com>

#项目目录变量
root=/usr/vmosc/
export PATH=$PATH:/usr/vmosc/bin
source /etc/profile

#按现有物理内存的1.5倍增加虚拟内存
function SetSwap(){
    local swap=/home/swap
    local MemTotal=$(awk '($1 == "MemTotal:"){print $2}' /proc/meminfo)
    local MemSwap=$((MemTotal+MemTotal/2))
    dd if=/dev/zero of=${swap} bs=1024 count=${MemSwap}  
    mkswap ${swap};swapon ${swap};chmod 600 ${swap}   
    echo "${swap} swap swap defaults 0 0" >> /etc/fstab 
    local SwpPiness=$(cat /proc/sys/vm/swappiness)
    if [ "$SwpPiness" -lt "60" ];then 
        sysctl vm.swappiness=60  
        echo "vm.swappiness = 60" >> /etc/sysctl.conf
    fi
}

#修改默认安装Caddy的目录
function SetCaddy(){
    mkdir -p ${root}bin/;mkdir -p ${root}config/;mkdir -p ${root}system/;mkdir -p ${root}view/www/
    mv /usr/bin/caddy ${root}bin/
    mv /etc/caddy/Caddyfile ${root}config/;
    mv /usr/share/caddy/index.html ${root}view/www/
    mv /usr/lib/systemd/system/caddy.service ${root}system/
    mv /usr/lib/systemd/system/caddy-api.service ${root}system/
    rm -rf /etc/caddy/;rm -rf /usr/share/caddy/
    sed -i 's/\/usr\/bin\//\/usr\/vmosc\/bin\//g' ${root}system/caddy.service
    sed -i 's/\/usr\/bin\//\/usr\/vmosc\/bin\//g' ${root}system/caddy-api.service
    sed -i 's/\/etc\/caddy\//\/usr\/vmosc\/config\//g' ${root}system/caddy.service
    ln -s ${root}system/caddy.service /usr/lib/systemd/system/caddy.service
    ln -s ${root}system/caddy-api.service /usr/lib/systemd/system/caddy-api.service
}

#设置主站
function SetSite(){
    :> /usr/vmosc/config/Caddyfile
    cat > /usr/vmosc/config/Caddyfile <<EOF
{
    email wangtl2001@163.com
}
www.vmosc.com {
    #header / Strict-Transport-Security "max-age=63072000"
    #encode gzip
	root * /usr/vmosc/view/www
	file_server
}
git.vmosc.com {
    reverse_proxy :3000
}
EOF
}

#更新Caddy配置文件
function LoadCaddy(){
    cd /usr/vmosc/config/
    caddy fmt --overwrite
    caddy reload
}

#安装Caddy
function Caddy(){
    #使用yum安装Caddy,适用CentOS7.X系统
    yum -y install yum-plugin-copr
    yum -y copr enable @caddy/caddy
    yum -y install caddy
    SetCaddy
    SetSite
    LoadCaddy
    systemctl enable --now caddy 
}
SetSwap
Caddy
